package com.keter.config;

import com.keter.security.AuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * 资源服务器
 */
@Configuration
@EnableResourceServer
public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(OAuth2ResourceServer.class);

    @Bean
    RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @Autowired
    private AuthenticationFilter authenticationFilter;
    @Autowired
    private UserDetailsService userDetailsService;

    /* 允许自由访问的URL */
    public static final String[] FREE_URL_PATTERNS = {
            "/public/**",
            "/v2/api-docs",
            "/swagger-resources/**",
            "/swagger-ui.html"
            /*Probably not needed*/
            ,"/swagger.json"
    };
    
    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        //开放访问
        permitAll(httpSecurity);
        httpSecurity
                // 由于使用的是JWT，我们这里不需要csrf
                .csrf().disable()
                .cors() //配合CorsConfig完成跨域认证的支持
                .and()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                //注销由客户端实现：删除token即可
                .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        ;
        // 禁用缓存
        httpSecurity.headers().cacheControl();
    }

    private void permitAll(HttpSecurity httpSecurity){
        Arrays.stream(FREE_URL_PATTERNS).forEach(s -> {
            try {
                httpSecurity.authorizeRequests().antMatchers(s).permitAll();
            } catch (Exception e) {
                logger.info("", e);
            }
        });
    }
}
